<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="8">
        <CategoryTabs @category-changed="clickCategory" />
        <!-- 推荐-信息流 -->
        <div v-if="category.label == '推荐'" class="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4"
          style="align-items: start;">
          <AppCard v-for="(post, index) in AppCardData" :key="index" :post="post" @like="handleLike(index)"
            :class="showCardI == index ? 'cardBor' : ''" @collect="handleCollect(index)"
            @toUrl="showComment('app', post.id, index)" class="postcard mt-6" />
        </div>

        <!-- 真实反馈-信息流 -->
        <div v-if="category.label == '真实反馈'" class="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4"
          style="align-items: start;">
          <CaseCard v-for="(post, index) in CaseCardData" :key="index" :post="post" @like="handleLike(index)"
            :class="showCardI == index ? 'cardBor' : ''" @collect="handleCollect(index)"
            @toUrl="showComment('case', post.id, index)" class="postcard mt-6" />
        </div>

        <div v-if="category.label != '真实反馈' && category.label != '推荐'"
          class="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4" style="align-items: start;">
          <CaseCard v-for="(post, index) in WenCardData" :key="index" :post="post" @like="handleLike(index)"
            :class="showCardI == index ? 'cardBor' : ''" @collect="handleCollect(index)"
            @toUrl="showComment('article', post.id, index)" class="postcard mt-6" />
        </div>
      </el-col>
      <el-col :span="16">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['demo:comment:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['demo:comment:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['demo:comment:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['demo:comment:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="commentList" default-expand-all row-key="id"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" align="center" prop="id" />
          <el-table-column label="评论用户" align="center" prop="nickName" />
          <el-table-column label="被回复用户" align="center" prop="otherNickName" />
          <el-table-column label="评论内容" align="center" prop="content" />
          <el-table-column label="喜欢数量" align="center" prop="likes" width="135">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.likes" controls-position="right" @change="handleChange(scope.row)"
                :min="1" :max="1000" label="" style="width:125px;"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="发布时间" align="center" prop="publishTime" width="140">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="评论类型：article-文章评论 case-案例库文章评论" align="center" prop="type" /> -->
          <!-- <el-table-column label="文章ID" align="center" prop="articleId" /> -->
          <!-- <el-table-column label="父评论ID，0表示顶级评论" align="center" prop="parentId" /> -->
          <!-- <el-table-column label="被回复者openId" align="center" prop="otherOpenId" /> -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['demo:comment:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['demo:comment:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 添加或修改评论对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="beautiful-form">

        <el-row class="beautiful-row">
          <el-col :span="24">


            <el-form-item label="评论内容" prop="content">
              <el-input v-model="form.content" placeholder="请输入内容" type="textarea" :rows="5"
                class="beautiful-textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-divider>用户信息</el-divider>
          </el-col>
          <el-col :span="8">

            <el-form-item label="评论者" prop="openId">
              <el-select v-model="form.openId" placeholder="请选择评论者" @change="changeCustomer" class="full-width-select">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.openId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker clearable v-model="form.publishTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择发布时间" class="full-width-date-picker">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="被回复者" prop="otherOpenId">
              <el-select v-model="form.otherOpenId" placeholder="请选择回复谁" @change="changeCustomer"
                class="full-width-select">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.openId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listComment, getComment, delComment, addComment, updateComment } from "@/api/demo/comment";


import CategoryTabs from '../../components/CategoryTabs.vue'
import AppCard from '../../components/AppCard.vue'
import CaseCard from '../../components/CaseCard.vue';
import { listCustomer } from "@/api/demo/customer";
import { listCover, getCover, updateCover } from "@/api/demo/cover";
import { listLibrary, getLibrary, updateLibrary } from "@/api/demo/library";
import { listArticle, getArticle, updateArticle } from "@/api/demo/article";


export default {
  name: "Comment",
  components: { CategoryTabs, AppCard, CaseCard },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评论表格数据
      commentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null,
        type: null,
        articleId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        openId: [
          { required: true, message: "评论者不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "评论内容不能为空", trigger: "blur" }
        ],
        publishTime: [
          { required: true, message: "发布时间不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "评论类型不能为空", trigger: "change" }
        ],
        articleId: [
          { required: true, message: "文章信息不能为空", trigger: "blur" }
        ],
      },

      baseApi: process.env.VUE_APP_BASE_API,
      category: { id: 0, label: "推荐" },
      customerList: [],
      AppCardData: [],
      CaseCardData: [],
      WenCardData: [],
      showCardI: null,

    };
  },
  created() {
    this.init()

    // this.getList();
  },
  methods: {
    init() {
      listCustomer().then(response => {
        this.customerList = response.rows
      })
      listCover().then(response => {
        let AppCardData = []
        response.rows.forEach(post => {
          AppCardData.push({
            id: post.id,
            imageUrl: this.baseApi + post.image,
            subTitle: post.subtitleTitle,
            // content: post.content,
          })
        })
        this.AppCardData = AppCardData
        console.log("AppCardData", this.AppCardData)

      })
      listLibrary().then(response => {
        let CaseCardData = []
        response.rows.forEach(post => {
          // console.log("post",post.publishAddress)
          CaseCardData.push({
            id: post.id,
            imageUrl: this.baseApi + post.imageUrl,
            title: post.title,
            content: post.content,
            // location: this.formatRegionDisplay(post.publishAddress),
            likes: post.likes,
            comments: post.comments,
            collects: post.collects,
          })

        })
        this.CaseCardData = CaseCardData
        console.log("CaseCardData", this.CaseCardData)
      })
    },
    getWenList() {
      listArticle({labelIds:this.category.id}).then(response => {
        let WenCardData = []
        response.rows.forEach(post => {
          WenCardData.push({
            id: post.id,
            imageUrl: this.baseApi + post.image,
            title: post.title,
            content: post.content,
            likes: post.likes,
            comments: post.comments,
            collects: post.collects,
            likes: post.likes,
          })
        })
        this.WenCardData = WenCardData
      })
    },

    clickCategory(e) {
      console.log(e)
      this.showCardI = null
      this.category = e
      if (e.id > 0) {
        this.getWenList()
      }
    },
    showComment(type, id, i) {
      this.queryParams.type = type
      this.queryParams.articleId = id
      this.showCardI = i
      this.getList()
    },
    handleChange(e) {
      console.log(e)
      updateComment(e).then(response => {
      })
    },




    /** 查询评论列表 */
    getList() {
      this.loading = true;
      listComment(this.queryParams).then(response => {
        this.commentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        openId: null,
        content: null,
        publishTime: null,
        type: null,
        articleId: null,
        parentId: null,
        otherOpenId: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.queryParams.articleId == null) {
        this.$modal.msgError("请选择文章")
        return
      }
      this.reset();
      this.form.type = this.queryParams.type
      this.form.articleId = this.queryParams.articleId
      this.open = true;
      this.title = "添加评论";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getComment(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改评论";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateComment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addComment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除评论编号为"' + ids + '"的数据项？').then(function () {
        return delComment(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/comment/export', {
        ...this.queryParams
      }, `comment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.beautiful-form {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.beautiful-form ::v-deep .el-form-item {
  margin-bottom: 22px;
}

.beautiful-form ::v-deep .el-form-item__label {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.full-width-select ::v-deep .el-input__inner {
  height: 40px;
  line-height: 40px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
}

.full-width-select ::v-deep .el-input__inner:focus {
  border-color: #409eff;
}

.beautiful-textarea ::v-deep .el-textarea__inner {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  padding: 12px;
  font-size: 14px;
  resize: vertical;
}

.beautiful-textarea ::v-deep .el-textarea__inner:focus {
  border-color: #409eff;
}

.full-width-date-picker ::v-deep .el-input__inner {
  width: 100%;
  height: 40px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
}

.full-width-date-picker ::v-deep .el-input__inner:focus {
  border-color: #409eff;
}

.dialog-footer {
  padding: 20px 30px;
  text-align: right;
  box-sizing: border-box;
}

.dialog-footer .el-button {
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 6px;
}
</style>